<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<jsp:include page="../../common.jsp"></jsp:include>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户信息</title>

<script type="text/javascript">
$(function () {

    //1.初始化Table
    var oTable = new TableInit();
    oTable.Init();

    //2.初始化Button的点击事件
    var oButtonInit = new ButtonInit();
    oButtonInit.Init();
	//初始化提示框的位置：top-center，bottom-left，bottom-right
    toastr.options.positionClass = 'toast-top-center';
	
    $('#pass').change(function () {
    	$("#pass2").val("");
    });
	
	
	//模态框关闭事件
    $('#exampleModal').on('hide.bs.modal',function(){
		$('#roleId').val("").trigger('change');
		$('#staffId').val("").trigger('change');
		
    	//表单清空
    	$("#fm")[0].reset();
    	//表单验证清空
    	$('#fm').data('bootstrapValidator').resetForm(true);
    });
    
    
  	//jQuery，既阻止默认行为又停止冒泡  导入按钮
    $(".submit").on('click',function(){
    	    return false;//当然 也阻止了事件本身
    });

});


var TableInit = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function () {
        $('#tb_table').bootstrapTable({
            url: '${pageContext.request.contextPath }/upmsStaffRole/list.do',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            sortable: false,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber:1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 20, 30],        //可供选择的每页的行数（*）
            strictSearch: true,
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 550,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "userRoleId",                     //每一行的唯一标识，一般为主键列
            detailView: false,                   //是否显示父子表
            columns: [{
                checkbox: true
            }, {
                field: 'userRoleId',
                title: 'id',
                visible: false
            }, {
                field: 'upmsRole.name',
                title: '名称'
            }, {
                field: 'upmsRole.title',
                title: '标题'
            }, {
                field: 'upmsStaff.scode',
                title: '工号'
            }, {
                field: 'upmsStaff.sname',
                title: '姓名'
            }]
        });
    };

    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
      		page: params.offset/params.limit+1,   //页面大小
            pageSize: params.limit,  //页码
            roleId:$.trim($('#roleIdTJ').val()), 
            staffId:$.trim($('#staffIdTJ').val()),    
        };
        return temp;
    };
    return oTableInit;
};


var ButtonInit = function () {
    var oInit = new Object();
    var postdata = {};

    oInit.Init = function () {
        //初始化页面上面的按钮事件
    };

    return oInit;
};

//判断本页是否数据是否为空，如果为空跳转至第一页
function refresh(){
	setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
		var row=$('#tb_table').bootstrapTable('getData');
		if(row.length == 0){
			$("#tb_table").bootstrapTable("refreshOptions",{pageNumber:1});
		}
	},1000);
}
//删除
function doDelete() {
	var row = $.map($("#tb_table").bootstrapTable('getSelections'),function(row){
		return row ;
	});
	if (row.length == 0) {
		toastr.warning('请至少选择一条数据!');
	}else{
		var ids = "";
		var names = "";
		for(var i = 0;i < row.length;i++){
			if(i == 0 || i == "0"){
				ids += row[i].userRoleId;
			}else{
				ids += "," + row[i].userRoleId;
			}
		}
		
		//询问框
		Ewin.confirm({ message: "确认要删除选择的数据吗？" }).on(function (e) {
	       if (!e) {
	         return;
	       } 
	    	var url = "${pageContext.request.contextPath }/upmsStaffRole/delete.do";
		    $.post(url, "ids="+ids, function(data) {
				if (data == 1) {
					toastr.success('删除成功');
					setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
						$('#tb_table').bootstrapTable('refresh');
						refresh();
					},1000);
				} else {
					toastr.error('删除失败');
					setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
						$('#tb_table').bootstrapTable('refresh');
						refresh();
					},1000);
				}
			}); 
	    }); 
	}
}
//打开添加框
function doAdd() {
	
	$("#bt").html("新增用户信息(默认密码为123)");
	$("#pass").val("123");
	$("#pass2").val("123"); 
	$("#userRoleId").val("");
	$('#roleId').val("").trigger('change');
	$('#staffId').val("").trigger('change');
	$('#exampleModal').modal(open);
}

//打开修改框
function doView() {
	//取表格的选中行数据
    var row = $("#tb_table").bootstrapTable('getSelections');
	if (row.length == 1) {
		$("#bt").html("修改用户信息");

		$("#userRoleId").val(row[0].userRoleId);
		
		$('#roleId').val(row[0].roleId).trigger('change');
		$('#staffId').val(row[0].staffId).trigger('change');
		/* $("#roleId").val(row[0].roleId).select2()
		$("#staffId").val(row[0].staffId).select2()  */
		$('#exampleModal').modal(open);
	}else{
		toastr.warning('请选择一条数据!');
	}
}
//表单提交
function save() {
    var bootstrapValidator = $("#fm").data('bootstrapValidator');  
    //开启验证
    bootstrapValidator.validate();  
    if (bootstrapValidator.isValid()){
		var url = "";
		var title = "";
    	if (document.getElementById('userRoleId').value == '') {
			url = "${pageContext.request.contextPath }/upmsStaffRole/add.do";
			title = "新增";
    	} else {
			url = "${pageContext.request.contextPath }/upmsStaffRole/update.do";
			title = "修改";
    	}  
	    $.post(url, $("#fm").serialize(), function(data) {
			if (data == 1) {
				toastr.success(title+'成功');
				setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
					$('#exampleModal').modal('hide');
					$('#tb_table').bootstrapTable('refresh');  
					refresh();
				},1000);
			} else {
				toastr.error(title+'失败');
			}
		});
    }else{
	    return;  
    } 
}
//刷新表格
function seach() {
	$("#tb_table").bootstrapTable("refreshOptions",{pageNumber:1});
}
</script>
</head>
<body>
	<div class="panel-body" style="padding-bottom:0px;">
        <div class="panel panel-default">
            <div class="panel-heading">查询条件</div>
            <div class="panel-body">
                <form id="formSearch" class="form-horizontal">
                    <div class="form-group" style="margin-top:15px">
                        <label class="control-label col-sm-1" for="roleIdTJ">角色</label>
                        <div class="col-sm-3">
                        	<select id="roleIdTJ" class="form-control select2">
                        		<option value="">请选择</option>
		            		</select>
                        </div>
                        <label class="control-label col-sm-1" for="staffIdTJ">姓名</label>
                        <div class="col-sm-3">
                            <select id="staffIdTJ" class="form-control select2">
                        		<option value="">请选择</option>
		            		</select>
                        </div>
                        <div class="col-sm-4">
                            <button type="button" style="margin-left: 20%;" id="btn_query" class="btn btn-primary" onclick="seach()">查询</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>       

		


        <div id="toolbar" class="btn-group">
            <button id="btn_add" type="button" class="btn btn-default" onclick="doAdd()">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
            </button>
            <button id="btn_edit" type="button" class="btn btn-default" onclick="doView()">
           		 <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
            </button>
            <button id="btn_delete" type="button" class="btn btn-default" onclick="doDelete()">
                <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
            </button>
            <button id="btn_add" type="button" class="btn btn-default" onclick="douploadModal()">
                <span class="glyphicon glyphicon-bullhorn" aria-hidden="true"></span>导入
            </button>
            <button id="btn_delete" type="button" class="btn btn-default" onclick="doExportall()">
                <span class="glyphicon glyphicon-export" aria-hidden="true"></span>导出所有
            </button>
             
            
            <script type="text/javascript">
	        	function doExportall() {
	        		Ewin.confirm({message : "确认导出所有数据吗？"}).on(
    					function(e) {
   						if (!e) {return;}
						window.location.href="${pageContext.request.contextPath}/upmsStaffRole/doExportall.do"; 
					})
				}
	        	
	        	function douploadModal() {
	        		$('#uploadModal').modal(open);
	        		//清空表单
	        		document.getElementById("importForm").reset();
	        	}
	        	
	        	function uploadBtn() {
	        		 var fileName = $("#fileInput").val();
	        		 if (fileName.length > 0) {
	        		     var formData = new FormData($("#importForm")[0]);  
	        		     $.ajax({  
	        		          url: '${pageContext.request.contextPath}/upmsStaffRole/uplodeFile.do' ,  
	        		          type: 'post',  
	        		          data: formData,
	        		          async: false,  
	        		          cache: false,  
	        		          contentType: false,  
	        		          processData: false,  
	        		          success: function (data) { 
	        		        	  if (data == 1) {
	        		        		  toastr.success("文件导入成功（不符合要求的数据直接过滤）！");
	        		        		  setTimeout(function() {//使用setTimeout()方法设定定时2000毫秒
	        		        		    $('#uploadModal').modal('hide'); 
	        		        		   $('#tb_table').bootstrapTable('refresh'); 
	        						  },1000);
	        		        	  }else if(data == -1){
	        		        		  toastr.warning("导入的数据不符合导入条件（人员不能重复或找不到对应的角色或员工）！");  
	        		        	  }else{
	        		        		  toastr.warning("文件格式异常，文件导入失败！");  
	        		        	  }
	        		          },  
	        		          error: function (data) {
	        		        	  toastr.error("文件格式异常，文件导入失败！");  
	        		          }  
	        		     }); 
	        		 }else{
	        			 toastr.warning("上传文件为空，请选择要导入的文件！");  
	        		}
	        	}
	        	
            </script>
        </div>
        <table id="tb_table"></table>
    </div>
    
    <div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
   		<div class="modal-dialog" role="document">
    		<div class="modal-content">
      			<div class="modal-header">
        			<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        			<h4 class="modal-title" id="exampleModalLabel">
        				<span>excel导入</span>
        			</h4>
      			</div>
      			<div class="modal-body">
	          		<div style="text-align:right;padding:5px">
                        <a href="${pageContext.request.contextPath }/data/upmsStaffRole.xls" onclick="javascript:Preview();">
                            <img alt="导入用户信息-模板" src="${pageContext.request.contextPath }/image/excel_alt_1.png" style="width: 20px;"/>
                            <span style="font-size:larger;font-weight:200;color:red">upmsStaffRole-模板.xls</span>
                        </a>
                    </div>
	        		<form id="importForm" class="form-horizontal">
	          			<div title="Excel导入操作" style="padding: 5px">
					            <input id="fileInput" name="file" type="file" accept=".xls,.xlsx"/>
	          			</div>
	        		</form>
	        		 <!--数据显示表格-->
                    <table id="gridImport" class="table table-striped table-bordered table-hover" cellpadding="0" cellspacing="0" border="0">
                    </table>
	      		</div>
       			<div class="modal-footer"> 
				        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
				        <button type="submit"  name="submit"  class="btn btn-primary submit" onclick="uploadBtn()">导入</button>
	      		</div>
    		</div>
  		</div>
	</div>
	
	
	
    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
   		<div class="modal-dialog" role="document">
    		<div class="modal-content">
      			<div class="modal-header">
        			<button type="button" class="close closefm" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        			<h4 class="modal-title" id="exampleModalLabel">
        				<span id="bt" style="font-size:13px"></span>
        			</h4>
      			</div>
      			<div class="modal-body">
	          		<form id="fm" class="form-horizontal">
	          			<div class="form-group">
	           				 <label class="col-sm-2 control-label">角色:</label>
	            			 <div class="col-sm-8"> 
		            			 <select id="roleId" name="roleId" class="form-control select2">
		            			 </select>
		            			 <input type="hidden" id="userRoleId" name="userRoleId" >
		          				 <span class="xing"></span>
		          				 <script type="text/javascript">
		          				$(function () {
			          				  $.ajax({
			          	                type: "post",
			          	                url: "${pageContext.request.contextPath }/upmsRole/queryAll.do",
			          	                dataType: 'JSON',
			          	                async: false,
			          	                success: function (arr) {
			          				    	var data = [];
			          				        for(var i=0;i<arr.length;i++){
			          					  		data.push({id:arr[i].roleId, text:arr[i].name});
			          				        }
			          				    	$('#roleId').select2({ 
			          				    	  allowClear: true,//清除
			          				    	  //multiple:true,
			          				    	  //tags: true,
			          			              //maximumSelectionLength: 1,  //设置最多可以选择多少项
			          				    	  minimumResultsForSearch: -1, //去模糊查询
			          				    	  language: "zh-CN", //设置 提示语言
			          				          width: "100%", //设置下拉框的宽度
			          				          placeholder: "请选择",
			          				      	  data: data
			          				      });
			          				    	
			          				    	$('#roleIdTJ').select2({ 
			          				    	  allowClear: true,//清除
			          				    	  //multiple:true,
			          				    	  //tags: true,
			          			              //maximumSelectionLength: 1,  //设置最多可以选择多少项
			          				    	  minimumResultsForSearch: -1, //去模糊查询
			          				    	  language: "zh-CN", //设置 提示语言
			          				          width: "100%", //设置下拉框的宽度
			          				          placeholder: "请选择",
			          				      	  data: data
			          				      });
			          	                }
			          				  });
		          				});

		          				 </script>
	          				</div>
	          			</div>
	          			<div class="form-group">
	           				 <label class="col-sm-2 control-label">人员:</label>
	            			 <div class="col-sm-8"> 
		            			 <select id="staffId" name="staffId" class="form-control select2">
		            			 </select>
		            			 <script type="text/javascript">
		          				$(function () {
			          				  $.ajax({
			          	                type: "post",
			          	                data:"sreserve1 = 1",
			          	                url: "${pageContext.request.contextPath }/upmsStaff/queryAll.do",
			          	                dataType: 'JSON',
			          	                async: false,
			          	                success: function (arr) {
			          				    	var data = [];
			          				        for(var i=0;i<arr.length;i++){
			          					  		data.push({id:arr[i].staffId, text:arr[i].sname});
			          				        }
			          				    	$('#staffId').select2({ 
			          				    		allowClear: true,//清除
			          				    	  	//multiple:true,
			          				    	  	//tags: true,
			          			              	//maximumSelectionLength: 1,  //设置最多可以选择多少项
			          				    	  	minimumResultsForSearch: -1, //去模糊查询
			          				    	  	language: "zh-CN", //设置 提示语言
			          				          	width: "100%", //设置下拉框的宽度
			          				          	placeholder: "请选择",
			          				      	  	data: data
			          				      });
			          	                }
			          				  });
			          				  
			          				  $.ajax({
			          	                type: "post",
			          	                url: "${pageContext.request.contextPath }/upmsStaff/queryAll.do",
			          	                dataType: 'JSON',
			          	                async: false,
			          	                success: function (arr) {
			          				    	var data = [];
			          				        for(var i=0;i<arr.length;i++){
			          					  		data.push({id:arr[i].staffId, text:arr[i].sname});
			          				        }
			          				    	$('#staffIdTJ').select2({ 
				          				    	  allowClear: true,//清除
				          				    	  //multiple:true,
				          				    	  //tags: true,
				          			              //maximumSelectionLength: 1,  //设置最多可以选择多少项
				          				    	  minimumResultsForSearch: -1, //去模糊查询
				          				    	  language: "zh-CN", //设置 提示语言
				          				          width: "100%", //设置下拉框的宽度
				          				          placeholder: "请选择",
				          				      	  data: data
				          				      });
			          	                }
			          				  });
		          				});

		          				 </script>
	          				</div>
	          			</div>
	          			
	          			<div class="form-group">
							<label class="col-sm-2 control-label">密码:</label>
							<div class="col-sm-8"> 
								<input type="password" name="pass" id="pass" class="col-xs-12 col-sm-4 form-control"/>
	          				</div>
						</div>
	          			<div class="form-group">
							<label class="col-sm-2 control-label">确认密码:</label>
							<div class="col-sm-8"> 
								<input type="password" name="pass2" id="pass2" class="col-xs-12 col-sm-4 form-control"/>
							</div>
						</div>
	          			
	        		</form>
	      		</div>
       			<div class="modal-footer"> 
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
				    <button type="submit" class="btn btn-primary submit" onclick="save()">保存</button>
	      		</div>
    		</div>
  		</div>
	</div>
    
    
      
	
	<script type="text/javascript">
	$(function() {
		$("#fm").bootstrapValidator({
			feedbackIcons : {
				valid : 'glyphicon glyphicon-ok',
				invalid : 'glyphicon glyphicon-remove',
				validating : 'glyphicon glyphicon-refresh'
			},
			fields : {
				roleId : {
					validators : {
						notEmpty : {
							message : '角色不能为空'
						},
					}
				},
				staffId : {
					validators : {
						notEmpty : {
							message : '员工不能为空'
						},
						callback: {
                            message: '员工不能重复',
                            callback:function(value, validator){
                                var flg = false;
                                $.ajax({
                                    type:'post',
                                    data:'staffId='+value,
                                    url:'${pageContext.request.contextPath}/upmsStaffRole/queryAll.do',
					                dataType: 'JSON',
					                async: false,
                                    success:function (data) {
                                        if(data.length == 0){
                                            flg  = true;
                                        }else if(data.length == 1){
	                                        var ma = $.trim($('#userRoleId').val());
	                                        if (ma == data[0].userRoleId) {
	                                            flg  = true;
	                                        }else{
	                                        	flg = false;
	                                        }
                                        }else{
                                            flg = false;
                                        }

                                    }
                                });
                                return flg;
                            }
                        },
					}
				},
				
				pass : {
					validators : {
						/* notEmpty : {
							message : '密码不能为空'
						}, */
						/* callback: {
                            message: '请重新确认密码',
                            callback:function(value, validator){
                                var flg = false;
                                var ma = $.trim($('#pass2').val());
								if(value == null || value == ""){
									alert("kdjd")
									flg = true;
								}else{
									if(ma != null || ma != ""){
										flg = true;
									}
								}
                                return flg;
                            }
                        }, */
					}
				}, 
				
				pass2 : {
					validators : {
						/* notEmpty : {
							message : '密码不能为空'
						}, */ 
						callback: {
                            message: '与密码不等，请重新确认密码',
                            callback:function(value, validator){
                                var flg = false;
                                var ma = $.trim($('#pass').val());
								if(ma == null || ma == "" || ma == value){
									flg = true;
								}
                                return flg;
                            }
                        },
					}
				},
			},
		});
	});
	</script>
</body>
</html>